import '@css/common.scss'
import './style.scss'
import 'lazyload'

import $http from '@js/ajax'
import $api from '@js/api'
import $config from '@js/pages/index'

let _raload;
getDate()
bindF5()

function getDate(only) {
	if (_raload) {
		return
	}
	_raload = true
	$http.get($api.list).then((res) => {
		if (res.code === 200) {

			if (res.list.length > 0) {
				const _len = res.list.length
				document.querySelectorAll('.card-img').forEach((el, index) => {

					const _len = res.list.length
					if (index + 1 <= _len) {
						el.className += ' no-bg card-img-cur'
						el.querySelector('a').setAttribute('href', `${$config['DETAIL_URL']}?src=${res.list[index].replace('thumbnail','imgs')}`)
						let _img = document.createElement("img")
						_img.className = 'lazyload'
						_img.alt = 'shop-home-img'
						_img.setAttribute('data-src', res.list[index])
						_img.setAttribute('src', '')
						el.querySelector('a').appendChild(_img)
						el.querySelector('a').innerHTML += '<div class="absolute top-0 left-0 z-10 text-white"><i class="absolute antd-iconfont antd-zoomin"></i></div>'
						checkImg()
					} else {
						el.remove();
					}
				});
				lazyload()

			}
		}
		_raload = false
		document.querySelector('#ReloadIcon').className = 'antd-iconfont antd-sync'
	}).catch(err => {
		_raload = false
		document.querySelector('#ReloadIcon').className = 'antd-iconfont antd-sync'
		console.log(err)
	})
}

function checkImg(){
	
	document.querySelectorAll('.lazyload').forEach((el) => {
		el.onload = function() {
			if(this.height<120){
				const _scalH = this.height / 20
				const _scalW = 200 / 20
				let _width = (120 / _scalH) * _scalW

				this.style.maxWidth = _width + 'px'
				this.style.width = _width + 'px'
				this.style.height = '120px'
				this.style.position = 'absolute'
				this.style.zIndex = '10'
				this.style.left = '50%'
				this.style.marginLeft = -_width / 2 + 'px'
				this.style.transition = 'none'
				setTimeout(()=>{
					this.style.transition = 'all .4s linear'
				},100)
				return
			}else if(this.height>120&&this.src.search('http')>-1){
				this.style.position = 'absolute'
				this.style.zIndex = '10'
				this.style.top = '50%'
				this.style.marginTop = -(this.height / 2) + 'px'
				this.style.transition = 'none'
				setTimeout(()=>{
					this.style.transition = 'all .4s linear'
				},100)
				
			}
			
		}
	})
}
function bindF5() {
	document.querySelector('#Reload').onclick = function (e) {
		changeNav()
	}
}


function changeNav() {
	document.querySelector('#ReloadIcon').className += " reload"
	document.querySelectorAll('.card-img').forEach((el) => {
		el.remove();
	});
	for (let i = 0; i < 20; i++) {
		document.querySelector('#List').innerHTML += '<li class="card-img overflow-hidden inline-block ml-16 mr-20 mb-24 rounded-6 relative">' +
			'<a href="" target="_blank"></a>' +
			'</li>'
	}
	setTimeout(() => {
		getDate()
	}, 600)
}